const {
	Service
} = require('dx-router-admin')
const {
	UniIdPermissions
} = require('dx-func-entity')


module.exports = class Permission extends Service {
	constructor(ctx) {
		super(ctx)
		this.entity = UniIdPermissions;		
	}
	//初始化
	init() {
		
	}
	async createPermission(parent) {
		const {
			$dx
		} = this;
		const dbCmd = $dx.db.command;
		// 开启事务
		const transaction = await $dx.db.startTransaction();
		try {
			// 顶级
			const parentRes = await this.where('permission_id', parent.permission_id).find()
			const parentData = {
				permission_id: parent.permission_id,
				permission_type: parent.permission_type,
				permission_name: parent.name,
				comment: parent.comment,
				parent_id:''
			}
			// 不存在，添加
			if (!parentRes) {
				transaction.collection(this.entity.table).add(parentData);
			} else {
				transaction.collection(this.entity.table).doc(parentRes._id).update(parentData);
			}
			//添加子权限
			const childrenInsert = async (row, parentId) => {
				const res = await this.where('permission_id', row.permission_id).find();
				if (!!res && res.parent_id !== parentId) {
					// 存在，但是父级是其他的
					throw new Error('权限标识已经存在～');
				}
				let childData = {
					permission_id: row.permission_id,
					permission_type: row.permission_type,
					permission_name: row.name,
					comment: row.comment,
					parent_id:parentId
				}
				// 不存在，添加
				if (!res) {
					await transaction.collection(this.entity.table).add(childData);
				} else {
					await transaction.collection(this.entity.table).doc(res._id).update(childData)
				}
				// 有下级
				if (row.children.length) {
					await Promise.all(row.children.map(async item => {
						await childrenInsert(item, row.permission_id)
					}))
				}
			}
			// 添加子权限
			await Promise.all(parent.children.map(async item => {
				await childrenInsert(item, parent.permission_id);
			}))
			// 提交事务
			await transaction.commit();
		} catch (e) {
			console.log(e)
			await transaction.rollback()
			$dx.error('操作失败')
		}
	}
}
